/*
XPTracker - Alternative Agile Tracking Tool
Copyright (C) 2006-2009  Stephen Starkey

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
*/
package org.xptracker.persistence;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Aggregates Persistence Listeners into one interface
 */
public class AggregatePersistenceListeners implements PersistenceListener {
  private List<PersistenceListener> listeners = new ArrayList<PersistenceListener>();

  public AggregatePersistenceListeners(PersistenceListener... listeners) {
    this.listeners.addAll(Arrays.asList(listeners));
  }

  public void beforeInsert(Object o) {
    performAggregate(new AggregateFunction() {
      public void execute(PersistenceListener listener, Object o) {
        listener.beforeInsert(o);
      }
    }, o);
  }

  public void afterInsert(Object o) {
    performAggregate(new AggregateFunction() {
      public void execute(PersistenceListener listener, Object o) {
        listener.afterInsert(o);
      }
    }, o);
  }

  public void onDelete(Object o) {
    performAggregate(new AggregateFunction() {
      public void execute(PersistenceListener listener, Object o) {
        listener.onDelete(o);
      }
    }, o);
  }

  public void beforeUpdate(Object o) {
    performAggregate(new AggregateFunction() {
      public void execute(PersistenceListener listener, Object o) {
        listener.beforeUpdate(o);
      }
    }, o);
  }

  public void afterUpdate(Object o) {
    performAggregate(new AggregateFunction() {
      public void execute(PersistenceListener listener, Object o) {
        listener.afterUpdate(o);
      }
    }, o);
  }

  public void onCommit() {
    performAggregate(new AggregateFunction() {
      public void execute(PersistenceListener listener, Object o) {
        listener.onCommit();
      }
    }, null);
  }

  public void onRollback() {
    performAggregate(new AggregateFunction() {
      public void execute(PersistenceListener listener, Object o) {
        listener.onRollback();
      }
    }, null);

  }

  private void performAggregate(AggregateFunction function, Object o) {
    for(PersistenceListener listener: listeners) {
      function.execute(listener, o);
    }
  }

  private interface AggregateFunction {
    void execute(PersistenceListener listener, Object o1);
  }
}
